package com.alinesno.cloud.operation.cmdb.third.data;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.LinkedList;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alinesno.cloud.operation.cmdb.web.bean.FileMeta;

/**
 * 七牛文件上传工具类
 * 
 * @author LuoAnDong
 * @since 2018年9月16日 上午6:58:04
 */
@Component
public class QiniuUploadTool {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Value("${user.home}")
	private String logFileTmp; // 本地文件

	@Resource(name = "qiniuDataStoregeImpl")
	private DataStorege dataStorege;

	public String uploadFile(MultipartFile file) {

		try {
			String tempFolder = logFileTmp + File.separator + "upload_tmp";

			File f = new File(tempFolder);
			if (!f.exists()) {
				FileUtils.forceMkdir(new File(tempFolder));
			}
			logger.debug("上传临时目录:{}", tempFolder);

			byte[] bytes = file.getBytes();
			Path path = Paths.get(tempFolder + File.separator + file.getOriginalFilename());
			Files.write(path, bytes);

			logger.debug("path = {}", path.toFile().getAbsolutePath());

			String netPath = path.toFile().getAbsolutePath(); // dataStorege.uploadData(path.toFile().getAbsolutePath());
			return netPath;
		} catch (IOException e) {
			logger.error("图片上传错误:{}", e);
		}

		return null;
	}

	public LinkedList<FileMeta> uploadLocal(MultipartHttpServletRequest request , String stackFileExport) {
		LinkedList<FileMeta> files = new LinkedList<FileMeta>();
		FileMeta fileMeta = null;
		
		// 1. build an iterator
		Iterator<String> itr = request.getFileNames();
		MultipartFile mpf = null;

		// 2. get each file
		while (itr.hasNext()) {

			// 2.1 get next MultipartFile
			mpf = request.getFile(itr.next());
			logger.debug(mpf.getOriginalFilename() + " uploaded! " + files.size());

			// 2.2 if files > 10 remove the first from the list
			if (files.size() >= 10)
				files.pop();

			// 2.3 create new fileMeta
			fileMeta = new FileMeta();
			fileMeta.setFileName(mpf.getOriginalFilename());
			fileMeta.setFileSize(mpf.getSize() / 1024 + " Kb");
			fileMeta.setFileType(mpf.getContentType());

			try {
				fileMeta.setBytes(mpf.getBytes());

				// copy file to local disk (make sure the path "e.g. D:/temp/files" exists)
				String filePath = stackFileExport + File.separator + mpf.getOriginalFilename() ; 
				File f = new File(filePath).getParentFile() ; 
				if(!f.exists()) {
					FileUtils.forceMkdir(f);
				}
				FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(filePath));
				
				fileMeta.setFilePath(filePath); 

			} catch (IOException e) {
				logger.debug("上传文件错误:{}", e);
			}
			// 2.4 add to files
			files.add(fileMeta);
		}
		// result will be like this
		// [{"fileName":"app_engine-85x77.png","fileSize":"8
		// Kb","fileType":"image/png"},...]
		return files ;
	}

}
